<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vue</title>
  <script src="./js/vue.js"></script>
  <style>
    .error {
      color: red;
    }
  </style>
</head>

<body>
  <div id="app">
    <!-- v-red它不是内置指令，它就是自定义指令 -->
    <!-- 自定义指令就需要来定义它： 全局和局部  -->
    <!-- 在定义指令时，它会有5个钩子函数(自定义指令的生命周期函数) -->
    <div>
      <!-- 修饰符 -->
      <input v-validate.phone="setPhooneTip" type="text" v-model="phone">
      <span :class="{error:phooneTip==''?false:true}">{{phooneTip}}</span>
    </div>
    <div>
      <input v-validate.pass="setPasswordTip" type="text" v-model="password">
      <span :class="{error:passwordTip==''?false:true}">{{passwordTip}}</span>
    </div>

  </div>

  <script>
    const validation = {
      phone(el, binds) {
        if (!/^1[3-9]\d{9}$/.test(el.value) && el.value != '') {
          binds.value('手机号码不合法')
        } else {
          binds.value('')
        }
      },
      pass(el, binds) {
        if (el.value.length > 4) {
          binds.value('密码长度过长')
        } else {
          binds.value('')
        }
      }
    }


    // 指令中不能调用 vue实例中的配置数据,但是可以通过值的方式来变向传入(代理)
    Vue.directive('validate', (el, binds) => {
      // 它是一个对象,如果没有修饰符则为一个空对象
      const modifiers = binds.modifiers
      if (Object.keys(modifiers).length > 0) {
        Object.keys(modifiers).forEach(key => validation[key](el, binds))
      }
    })

    let vm = new Vue({
      el: '#app',
      data: {
        phone: '',
        phooneTip: '',
        password: '',
        passwordTip: ''
      },
      methods: {
        setPhooneTip(msg) {
          this.phooneTip = msg
        },
        setPasswordTip(msg) {
          this.passwordTip = msg
        }
      }
    })
  </script>
</body>

</html>